﻿#include<Windows.h>
#include<memory>
#include<string>
#include"SimpleWindow.h"
#include"SimpleRender.h"

int h = 600, w = 600;
sr::Render render(w, h);
bool run = false;
LRESULT WINAPI winproc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
	switch (msg)
	{
	case WM_CLOSE:
	{
		OutputDebugString(TEXT("WM_CLOSE\n"));
		PostQuitMessage(0);
		return 0;
	};
	case WM_KEYDOWN:
	{
		if (wparam == VK_LEFT)
		{
			render.getCamera().pos.x -= 0.1f;
			render.init();
		}
		else if (wparam == VK_RIGHT)
		{
			render.getCamera().pos.x += 0.1f;
			render.init();
		}
		else if (wparam == VK_UP)
		{
			render.getCamera().pos.y += 0.1f;
			render.init();
		}
		else if (wparam == VK_DOWN)
		{
			render.getCamera().pos.y -= 0.1f;
			render.init();
		}
	}
	case WM_LBUTTONDOWN:
	{
		run = !run;
	}
	default:
		break;
	};

	return DefWindowProc(hwnd, msg, wparam, lparam);
};
HDC mhdc;
HWND hwnd;

int WINAPI WinMain(HINSTANCE hinst, HINSTANCE ot, LPSTR cmd, int ncmd)
{

	if (!sw::registerWindowClass())
		return -1;
	hwnd = sw::createWindow(600,600);
	ShowWindow(hwnd, SW_SHOW);

	sw::setWindowProc(hwnd, winproc);

	HDC hdc = GetDC(hwnd);
	mhdc = CreateCompatibleDC(hdc);
	

	
	BITMAPINFO bmpinfo = {
		sizeof(BITMAPINFOHEADER),
			w,
			-h,
			1,
			32,
			BI_RGB,
			w * h * 4,
			0,
			0,
			0,
			0
	};
	LPVOID ptr = nullptr;
	auto hbitmap=CreateDIBSection(mhdc, &bmpinfo, DIB_RGB_COLORS, &ptr, nullptr, 0);
	auto oldObject=SelectObject(mhdc, hbitmap);

	for (int i = 0; i < h; i++)
	{
		for (int j = 0; j < w; j++)
		{
			((UINT*)ptr)[i * w + j] = 0xff0000;//a r g b
		}
	}

	BitBlt(hdc, 0, 0, w, h, mhdc, 0, 0, SRCCOPY);
	ReleaseDC(hwnd, hdc);

	render.f = [](HWND hwnd, HDC mhdc) {HDC hdc = GetDC(hwnd);
	BitBlt(hdc, 0, 0, w, h, mhdc, 0, 0, SRCCOPY);
	ReleaseDC(hwnd, hdc); };

	
	
	render.setFrameBuffer((UINT*)(ptr));
	render.init();

	MSG msg = {};

	
	bool status = true;
	while (status)
	{
		if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		};

		status =!( msg.message==WM_QUIT);
		
		//渲染器只负责输出帧
		//但不负责屏幕的刷新
		render.clear();
		render.draw();
		if(run)
			render.update();

		//update
		HDC hdc = GetDC(hwnd);
		BitBlt(hdc, 0, 0, w, h, mhdc, 0, 0, SRCCOPY);
		
		// TextOut(hdc, 10, 10, TEXT(""))
		ReleaseDC(hwnd,hdc);
		std::wstring buf;
		buf += L"view ("; buf += std::to_wstring(render.getCamera().pos.x);
		buf += L" "; buf += std::to_wstring(render.getCamera().pos.y);
		buf += L" "; buf += std::to_wstring(render.getCamera().pos.z);
		buf += L")";

		SetWindowText(hwnd, buf.c_str());

	}

	return 0;
};